package com.ipmirror.text;

import javax.faces.context.FacesContext;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Locale;
import java.util.ResourceBundle;

/**
 *
 *  @author 	 CM  
 *  @version     %I%, %G%
 *  @since       1.0    
 *
 */

public class MessageBundleLoader {
	
	public static final String MESSAGE_PATH = "com.ipmirror.text.messages";

	private static HashMap<String, ResourceBundle> messageBundles = new HashMap<String, ResourceBundle>();

	/**
	 * Gets a string for the given key from this resource bundle or one of its
	 * parents.
	 *
	 * @param key the key for the desired string
	 * @return the string for the given key.  If the key string value is not
	 *         found the key itself is returned.
	 */
	
	public static String getMessage(String key) {
	    if (key == null) {
	        return null;
	    }
	    try {
	        Locale locale =
	            FacesContext.getCurrentInstance().getViewRoot().getLocale();
	        if (locale == null) {
	            locale = Locale.ENGLISH;
	        }
	        ResourceBundle messages = (ResourceBundle)
	            messageBundles.get(locale.toString());
	        if (messages == null) {
	            messages = ResourceBundle.getBundle(MESSAGE_PATH, locale);
	            messageBundles.put(locale.toString(), messages);
	        }
	        return messages.getString(key);
	    }
	    // on any failure we just return the key, which should aid in debugging.
	    catch (Exception e) {
	        return key;
	    }
	}

    static public String getMessage(String template, Object... messageArgs) {
        return getMessage(null, MESSAGE_PATH, template, messageArgs);
    }

    static public String getMessage(Locale locale, String template, Object[] messageArgs) {
        return getMessage(locale, MESSAGE_PATH, template, messageArgs);
    }

    static public String getMessage(Locale locale, String baseName, String key) {
        if (locale == null) {
            locale = Locale.getDefault();
        }
        ResourceBundle res = ResourceBundle.getBundle(baseName, locale);
        String value = key;
        try {
            value = res.getString(key);
        } catch (NullPointerException e) { }
        return value;
    }	
	
    static public String getMessage(Locale locale, String baseName, String template, Object... messageArgs) {
        if (locale == null) {
          locale = Locale.getDefault();
      }
      ResourceBundle res = ResourceBundle.getBundle(baseName, locale);
      MessageFormat formatter = new MessageFormat("");
      formatter.setLocale(locale);
	    formatter.applyPattern(res.getString(template));
      return formatter.format(messageArgs);
  }        

}
